/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.web;

import com.google.inject.Inject;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.SimpleError;
import org.apache.commons.lang.StringUtils;
import org.xptracker.domain.Domain;
import org.xptracker.services.auth.Authenticator;

@UrlBinding("/Login.action")
public class LoginActionBean extends StandardActionBean {
  @SuppressWarnings({"UnusedDeclaration"})
  @Inject
  private Domain domain;

  @SuppressWarnings({"UnusedDeclaration"})
  @Inject
  private Authenticator authenticator;

  private String username;
  public String getUsername() { return username; }
  public void setUsername(String username) { this.username = username; }

  private String password;
  public String getPassword() { return password; }
  public void setPassword(String password) { this.password = password; }

  private String uri;
  public String getUri() { return uri; }
  public void setUri(String uri) { this.uri = uri; }

  @DefaultHandler
  public Resolution displayLoginPage() {
    return new ForwardResolution("/login.jsp");
  }

  @HandlesEvent("LoginEvent")
  public Resolution doLogin() {
    LoginFailure failure = LoginFilter.attemptLogin(authenticator, domain, getContext().getRequest(), username, password);
    if (failure != null) {
      getContext().getValidationErrors().add(failure.field.toString(),
          new SimpleError(failure.message + (failure.field == LoginField.username ? " ''{1}''" : ""), username));
      return new ForwardResolution("/login.jsp");
    }

    if (StringUtils.isNotBlank(uri)) {
      return new RedirectResolution(uri, false);
    }
    return new RedirectResolution(MainActionBean.class);
  }

  @After(stages=LifecycleStage.EventHandling)
  public void clearPassword() {
    password = null;
  }
}
